package com.hm.service.framework.request.post.v2;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.hm.service.framework.crypto.ECB.AES_ECB;
import com.hm.service.framework.crypto.KeyConstant;
import com.hm.service.framework.request.post.PostHandleBean;
import com.hm.service.framework.response.ResponseBean;
import com.hm.service.framework.session.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 统一处理请求
 * 加密/解密/都在这里完成
 */
public class PostControllerHelp_V2 {

    private static final Logger logger = LoggerFactory.getLogger(PostControllerHelp_V2.class);

    //处理session接口的请求
    public static PostHandleBean handleSessionRequest(String body) {
        PostHandleBean postHandleBean = new PostHandleBean();
        if (body == null || body.isEmpty()) {
            postHandleBean.setComplete(false);
            postHandleBean.setDes("请求体为空");
            return postHandleBean;
        }
        //用私钥解密
        String realBody = AES_ECB.decrypt(KeyConstant.PrivateSecretKeyMap.get(KeyConstant.SecretKeyVersion), body);
        boolean json = isJson(realBody);
        if (json) {
            //解密成功
            postHandleBean.setComplete(true);
            postHandleBean.setRealSecretKey(KeyConstant.PrivateSecretKeyMap.get(KeyConstant.SecretKeyVersion));
            postHandleBean.setReqBody(realBody);
        } else {
            //解密失败
            postHandleBean.setComplete(false);
            postHandleBean.setDes(realBody);
        }
        return postHandleBean;
    }

    //处理其他接口
    public static PostHandleBean handleNormalRequest(String requestUrl, String sessionId, String body) {
        PostHandleBean postHandleBean = new PostHandleBean();
        if (sessionId == null || sessionId.isEmpty()) {
            postHandleBean.setComplete(false);
            postHandleBean.setDes("sessionId为空");
            return postHandleBean;
        }
        if (body == null || body.isEmpty()) {
            postHandleBean.setComplete(false);
            postHandleBean.setDes("请求体为空");
            return postHandleBean;
        }
        //判断authorization的合法性
        HashMap<String, String> map = SessionUtils.verifier(sessionId);
        String state = map.get("state");
        String msg = map.get("msg");
        if (state.equals("0")) {
            //获取请求头携带的版本号->根据版本号拿到公钥
            String version = map.get("version");
            String privateKey = KeyConstant.PrivateSecretKeyMap.get(version);
            String publicKey = KeyConstant.PublicSecretKeyMap.get(version);
            //这里用固定密钥加解密
            String realKey = KeyConstant.PrivateSecretKeyMap.get(KeyConstant.SecretKeyVersion);
            //String realKey = algorithm(privateKey, publicKey);
            //用真实的key解密
            String realBody = AES_ECB.decrypt(realKey, body);
            boolean json = isJson(realBody);
            if (json) {
                //解密成功
                postHandleBean.setComplete(true);
                postHandleBean.setRealSecretKey(realKey);
                postHandleBean.setReqBody(realBody);
            } else {
                postHandleBean.setComplete(false);
                postHandleBean.setDes(realBody);
            }
        } else {
            //认证失败
            postHandleBean.setComplete(false);
            postHandleBean.setDes("sessionId认证失败:" + msg);
        }
        return postHandleBean;
    }

    public static <T> String generateSuccessResponse(String realSecretKey, int code, String des, T data) {
        ResponseBean<T> resultBean = new ResponseBean<>();
        resultBean.setCode(code);
        resultBean.setDes(des);
        resultBean.setData(data);
        String resultStr = JSON.toJSONString(resultBean);
        return AES_ECB.encrypt(realSecretKey, resultStr);
    }

    //错误状态的响应体不加密，因为失败的状态有很多种，没法拿到真实的密钥去加密
    public static <T> String generateErrorResponse(int code, String des, T data) {
        ResponseBean<T> resultBean = new ResponseBean<>();
        resultBean.setCode(code);
        resultBean.setDes(des);
        resultBean.setData(data);
        return JSON.toJSONString(resultBean);
    }

    //判断是否为json格式
    private static boolean isJson(String data) {
        if (data == null || data.isEmpty()) {
            return false;
        }
        try {
            JSON.parse(data);
        } catch (JSONException e) {
            logger.error("解密后为非json格式");
            return false;
        }
        return true;
    }

}
